package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;//CheckInMapper入住信息
    //自动注入mapper层对象
    @Autowired
    private ElderMapper elderMapper;//老人

    @Autowired
    private BedMapper bedMapper;//床位

    @Autowired
    private ContractMapper contractMapper;//签约办理

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;//入住配置


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {
        //1. 校验老人是否已经入住
        LambdaQueryWrapper<Elder> wrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder oldElder = elderMapper.selectOne(wrapper);
        if (oldElder != null) {//说明该老人已经入住
            return;
        }
        //2. 更新床位状态为已入住
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3. 新增或者更新老人表信息
        Elder elder = insertOrUpdateElder(dto, bed);
        // 新增签约办理
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        insertContract(contractNo, elder, dto);

        // 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);

        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);
    }

    /**
     * 新增入住配置
     *
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param checkInApplyDto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增合同
     *
     * @param contractNo
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {

        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(Long.valueOf(status));
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    /**
     * 有旧数据就更新,没有旧数据就插入
     *
     * @param dto
     */
    private Elder insertOrUpdateElder(CheckInApplyDto dto, Bed bed) {
        //先得到老人信息
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder newElder = new Elder();
        //属性拷贝
        BeanUtils.copyProperties(checkInElderDto, newElder);
        //添加老人表中的床位信息
        newElder.setBedId(bed.getId());//床位ID
        newElder.setBedNumber(bed.getBedNumber());//床位编号
        // 查询老人信息，（身份证号、状态不为1）
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(newElder);
        } else {
            // 新增
            elderMapper.insert(newElder);
        }
        return newElder;
    }

    @Override
    public CheckInDetailVo getDetail(Long id) {//TODO 注意这个id是入住表的id,不是老人表的id
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1. 封装家属信息
        //1.1 查询入住信息 根据老人id进行查询
        CheckIn checkIn = checkInMapper.selectById(id);
        //1.2 得到家属信息
        String elderFamilyInfo = checkIn.getRemark();
        if (elderFamilyInfo != null) {
            List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(elderFamilyInfo, ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        }
        //2.查询老人表
        //2.1 得到老人id
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getId, elderId));
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //属性赋值
        BeanUtils.copyProperties(elder, checkInElderVo);
        //计算年龄
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate birthday = LocalDate.parse(elder.getBirthday(), formatter);
        int age = Period.between(birthday, LocalDate.now()).getYears();
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //3. 查询入住配置
        //3.1 根据checkIn来查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        //3.2 属性拷贝
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        //3.3 填充入住配置信息字段 开始时间和结束时间在contract中
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elderId));
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);//入住配置信息
        //4. 查询合同信息
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
